package com.peng.job;

import com.peng.constants.RedisKey;
import com.peng.domain.entity.Article;
import com.peng.service.ArticleService;
import com.peng.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    @Scheduled(cron = "0 */10 * * * ?")
    public void updateViewCount() {
        // 获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(RedisKey.BLOG_VIEWCOUNT);
        List<Article> articles = viewCountMap.entrySet().stream()
                .map(new Function<Map.Entry<String, Integer>, Article>() {
                    @Override
                    public Article apply(Map.Entry<String, Integer> entry) {
                        return new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue());
                    }
                })
                .collect(Collectors.toList());
        // 更新到数据库中
        articleService.updateBatchById(articles);
    }

}
